import jwt from "jsonwebtoken"
import config from './config.js'
import axios from "axios"

/**
 * 设置数据返回格式及默认值
 * @param {*} ctx 
 * @param {*} next 
 * 
 * 之后的路由组件需要返回数据实例：['',0,null]
 * [
 *  0:"",返回文字描述
 *  1:0, 状态码，0错误，1正常，2需要登陆
 *  2：null,返回信息
 * ]
 */
export async function backStruct(ctx, next) {

    var data = await next();

    console.log('data', data);
    if (!data) {
        data = ['404', 0, data];
    }
    var isArray = data instanceof Array;
    if (!isArray) {
        data = ['需要返回数组', 0, data];
    }
    ctx.body = {
        code: data && data[1] ? data[1] : 0,
        msg: data && data[0] ? data[0] : "发生错误",

        data: data && data[2] ? data[2] : null,
    };
}

/**
 * 从token获取用户信息
 * @param {*} ctx koa
 * @param {*} next 
 */
export async function checkToken(ctx, next) {
    var token = ctx.query.token || ctx.request.body.token;
    if (!token) {
        return ["未登陆", 2];
    }
    var decoded = jwt.verify(token, config.secret);
    if (decoded && decoded.user) {
        ctx.user = decoded.user;
        return next();
    } else {
        return ["未登陆", 2, decoded];
    }
}
/**
 * 发生webhook
 * @param {*} ctx 
 * @param {*} next 
 */
export async function webhook(ctx, next) {
    var url = "https://oapi.dingtalk.com/robot/send?access_token=7090b66e7480c88dcd8b42516b8d8e41ba9c9557cf55d669aa3b21cef3080474";
    var sendData = {
        msgtype: 'text',
        text: {
            content: "我就是我, 是不一样的烟火"
        },
        "at": {
            "atMobiles": ["17608390654"],
            "isAtAll": false
        }
    }
    try {
        var data = await axios.post(url, sendData);//{"errcode":0,"errmsg":"ok"}
        console.log(data.data);
        if (data.data.errcode === 0) {
            return ["发生webhook成功", 1, data.data]
        }
        return ["发生webhook失败", 0, data.data]

    } catch (error) {
        return ["发生webhook失败", 0]
    }
}


export default {
    backStruct,
    checkToken,
    webhook
}